package com.gitee.kobe577590.generator;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gitee.kobe577590.validator.Validator;
import com.gitee.kobe577590.validator.exception.ValidateException;
import com.gitee.kobe577590.validator.rules.other.MustBeNotNull;
import com.gitee.kobe577590.validator.rules.string.StringMustBeRequired;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;

public abstract class AbstractGenerator {

	
	Map<String,Object> params = new HashMap<String,Object>();
	List<GeneratorItem> items = new ArrayList<GeneratorItem>();
	Engine engine;
	/**
	 * 读取模板内容信息 赋值 输出结果文件
	 * @throws ValidateException 
	 */
	public void execute() throws ValidateException {
		config(items);
		Validator v = new Validator();
		for (GeneratorItem generatorItem : items) {
			v.addRule(new StringMustBeRequired(generatorItem.getCodeTemplatePath(), "模板路径不能唯为空"));
			v.addRule(new StringMustBeRequired(generatorItem.getOutPutPath(), "文件输出路径不能唯为空"));
			v.addRule(new StringMustBeRequired(generatorItem.getOutPutPageName(), "输出文件名不能唯为空"));
			v.addRule(new MustBeNotNull(this.engine, "请配置模板引擎实例"));
			v.excute();
			System.out.println("开始生成文件"+generatorItem.getOutPutPageName());
			Template template = readTemplateContent(generatorItem);
			if(template!=null){
				String data = parseTemplate(template);
				createCodeFile(data,generatorItem);
				System.out.println("生成模板文件成功，请到路径:"+generatorItem.getOutPutPath()+"下查看，生成文件");
			}else{
				throw new ValidateException("模板对象不能为空");
			}
		}
		
		
	}

	public abstract void config(List<GeneratorItem> items );
	public Template readTemplateContent(GeneratorItem generatorItem){
			return this.engine.getTemplate(generatorItem.getCodeTemplatePath());
	}
	public abstract String parseTemplate(Template template);
	public void createCodeFile(String data,GeneratorItem generatorItem){
		try {
            File file = new File(generatorItem.getOutPutPath());
            if(!file.exists()){
                file.mkdirs();
            }
            FileOutputStream o=null;
            o = new FileOutputStream(file+File.separator+generatorItem.getOutPutPageName());
            o.write(data.getBytes("UTF-8"));
            o.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}
